﻿using NB.MGJ.Common.API;
using NB.MGJ.Common.Helper;
using NB.MGJ.Common.Utility;
using NB.MGJ.Model;
using NB.MGJ.Model.Model;
using NB.MGJ.Service;
using NB.MGJ.Service.Product;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.WebPages.Html;

namespace NB.MGJ.API
{
    [ApiAuthorizeFilter]
    [ApiHandleError]
    public partial class ApiMGJFleedToolsController : ApiBaseController<LogOnUserModel>
    {
        public CommonService cs = new CommonService();
        public ProductBatchService _ProductBatchService = new ProductBatchService();
        public ManagerService _mservice = new ManagerService();
        public FleeGoodsService _flee = new FleeGoodsService();
        public Sys_User user = new Sys_User();
        //片区下拉框
        [Route("nbapi/salesarea/selectitem")]
        [HttpGet]
        public IHttpActionResult GetSalesAreaNameList(int userId)
        {


            //根据用户id得到用户信息
            Sys_User userInfo = _mservice.GetUserInfoById(userId);
            IEnumerable<SelectItem> result;

            if (userInfo.Distributor != 0)//经销商
            {
                result = _flee.GetSaleAreaServiceApp(userInfo.Distributor.Value);
            }
            else
            {

                result = _flee.GetSaleAreaServiceApp(userInfo.EnterpriseId.ToString());
            }


            return ApiSuccess(result);

        }
        //经销商下拉框
        [Route("nbapi/distributor/dselectitem")]
        [HttpGet]
        public IHttpActionResult GetDistributorList(int userId, int areaid = 0)
        {

            //根据用户id得到用户信息
            Sys_User userInfo = _mservice.GetUserInfoById(userId);
            IEnumerable<SelectItem> result;
            if (userInfo.Distributor != 0)//经销商
            {
                result = _flee.GetDistributorServiceApp(areaid, userInfo.Distributor.Value);
            }
            else
            {
                result = _flee.GetDistributorServiceApp(areaid);
            }
            return ApiSuccess(result);

        }
        //仓库下拉框
        [Route("nbapi/warehouse/wselectitem")]
        [HttpGet]
        public IHttpActionResult GetwarehouseList(int userId)
        {

            Sys_User userInfo = _mservice.GetUserInfoById(userId);
            IEnumerable<SelectItem> result;
            if (LogOnUser.Distributor != 0)//经销商
            {
                result = _flee.GetWarehouseServiceApp(userInfo.ID);
            }
            else
            {
                //查询某机构下的所有仓库 包括其下级机构的仓库
                result = _flee.GetWarehouseServiceApp(userInfo.EnterpriseId.ToString());
            }
            return ApiSuccess(result);

        }
        //调拨仓库
        [Route("nbapi/warehouse/gowarehouseselect")]
        [HttpGet]
        public IHttpActionResult GetGoWarehouseList(int userId, int warehouseId)
        {
            Sys_User userInfo = _mservice.GetUserInfoById(userId);
            IEnumerable<SelectItem> result;
            if (LogOnUser.Distributor != 0)//经销商
            {
                result = _flee.GetWarehouseServiceApp(userInfo.ID, warehouseId);
            }
            else
            {
                //查询某机构下的所有仓库 包括其下级机构的仓库
                result = _flee.GetWarehouseServiceApp(userInfo.EnterpriseId.ToString(), warehouseId);
            }
            return ApiSuccess(result);
        }
        //产品下拉
        [Route("nbapi/product/pselectitem")]
        [HttpGet]
        public IHttpActionResult GetproductList(int userId, string productId = null)
        {

            Sys_User userInfo = _mservice.GetUserInfoById(userId);
            return ApiSuccess(_flee.GetProcductServiceApp(userInfo.EnterpriseId.ToString(), productId));

        }
        //出入库添加
        [Route("nbapi/Storage/pinStorage/add")]
        [HttpPost]
        public IHttpActionResult StorageAdd([FromBody]AntiFleeing_IOWarehouse model)
        {
            try
            {
                bool _Result = true;
                if (model == null)
                {
                    return ApiFail("当前无法执行该操作");
                }
                if (model.Codes == null)
                {
                    model.Codes = model.Codes_String.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
                }
                if (model.FormType == 1)
                {
                    _Result = ExecuteOfIn(model.Codes, model.FormCode, model.CreateLoginID.Value, model.WarehouseId.Value, int.Parse(model.ProductID));
                    model.FilePath = fs.WriteTxt(model.Codes, "RK" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".txt");
                }
                else if (model.FormType == 2)
                {

                    _Result = ExecuteOfOut(model.Codes, model.FormCode, model.Distributor.Value, int.Parse(model.ProductID));
                    model.FilePath = fs.WriteTxt(model.Codes, "CK" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".txt");
                }
                if (!_Result)
                {
                    if (model.FormType == 1)
                    {
                        return ApiFail("入库失败,请稍后重试");
                    }
                    return ApiFail("出库失败,请稍后重试");
                }
                int count = fs.SearchChildrenCount(model.Codes[0]);
                model.DragNum = count * model.Num;
                model.CreateDate = DateTime.Now;
                model.ViewDel = 0;
                model.Status = 2;//导入成功
                _flee.Add(model);
                return ApiSuccess(true);
            }
            catch (Exception ex)
            {

                return ApiFail(ex.Message);
            }

        }
        public bool ExecuteOfOut(string[] codes, string formCode, int distriButor, int proId)
        {
            //批量插入
            DataTable dt = new DataTable();
            dt.Columns.Add("FormCode", typeof(string));
            dt.Columns.Add("WLcode", typeof(string));
            dt.Columns.Add("DistributorID", typeof(int));
            dt.Columns.Add("CreateDate", typeof(DateTime));
            dt.Columns.Add("ChangeDate", typeof(DateTime));
            for (int i = 0; i < codes.Length; i++)
            {
                if (i == 0) dt.TableName = "nbcodemain.AntiFake_Digitcode" + codes[0].Substring(0, AppConst.SubStrLen);
                DataRow dr = dt.NewRow();
                dr["FormCode"] = formCode;
                dr["WLcode"] = codes[i];
                dr["DistributorID"] = distriButor;
                dr["CreateDate"] = DateTime.Now;
                dr["ChangeDate"] = DateTime.Now;
                dt.Rows.Add(dr);
            }
          return  _flee.ExecuteSqlTran(dt, proId, formCode, "ANTIFLEEING_OUTBOUNDDETAILS");

        }
        public bool ExecuteOfIn(string[] codes, string formCode, int uId, int warehouseId, int proId)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("WLcode", typeof(string));
            dt.Columns.Add("FormCode", typeof(string));
            dt.Columns.Add("UserID", typeof(int));
            dt.Columns.Add("WarehouseId", typeof(int));
            dt.Columns.Add("CreateDate", typeof(DateTime));
            dt.Columns.Add("ChangeDate", typeof(DateTime));
            for (int i = 0; i < codes.Length; i++)
            {
                if (i == 0) dt.TableName = "nbcodemain.AntiFake_Digitcode" + codes[0].Substring(0, AppConst.SubStrLen);
                DataRow dr = dt.NewRow();
                dr["WLcode"] = codes[i];
                dr["FormCode"] = formCode;
                dr["UserID"] = uId;
                dr["WarehouseId"] = warehouseId;
                dr["CreateDate"] = DateTime.Now;
                dr["ChangeDate"] = DateTime.Now;
                dt.Rows.Add(dr);
            }
            return _flee.ExecuteSqlTran(dt, proId, formCode, "ANTIFLEEING_WAREHOUSINGDETAILS");
        }

        //调拨添加
        [Route("nbapi/product/unboxing/add")]
        [HttpPost]
        public IHttpActionResult UnBoxingAdd([FromBody]AntiFleeing_Allocation model)
        {
            if (model == null)
            {
                return ApiFail("当前无法执行该操作");
            }
            DataTable dt = new DataTable();
            dt.Columns.Add("WLcode", typeof(string));
            dt.Columns.Add("FormCode", typeof(string));
            dt.Columns.Add("CreateDate", typeof(DateTime));
            if (model.Codes == null) { model.Codes = model.Codes_String.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); }
            for (int i = 0; i < model.Codes.Length; i++)
            {

                DataRow dr = dt.NewRow();
                dr["FormCode"] = model.FormCode;
                dr["WLcode"] = model.Codes[i];
                dr["CreateDate"] = DateTime.Now;
                dt.Rows.Add(dr);

            }
            try
            {
                //批量插入
                _flee.ExecuteOfBatch(dt, "ANTIFLEEING_ALLOCATIONDETAILS");
                //批量修改
                _flee.AllocationBatchUpdate(model.FormCode, model.GoWarehouseId.Value, model.FromWarehouseId.Value);
                int count = fs.SearchChildrenCount(model.Codes[0]);
                model.FilePath = fs.WriteTxt(model.Codes, "DB" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".txt");
                model.DragNum = count * model.Num;
                model.CreateDate = DateTime.Now;
                model.ViewDel = 0;
                model.Type = 3;//app添加
                model.Status = 2;//导入成功
                _mservice.UnBoxingAdd(model);
                return ApiSuccess(true);
            }
            catch (Exception ex)
            {

                return ApiFail(ex.Message);
            }

        }
        //退货添加
        [Route("nbapi/goods/return/add")]
        [HttpPost]
        public IHttpActionResult ProReturnLittleCode(AntiFleeing_ProductReturn model)
        {
            LogOnUserModel userModel = LogOnUser;
            // model.FormCode = _flee.ProReturnGetCode(userModel.EnterpriseId.ToString());
            if (model.Codes == null)
            {
                model.Codes = model.Code_String.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
            }
            string[] arr = model.Codes;
            Organization_Enterprise ent = _flee.GetEnterprise(LogOnUser.EnterpriseId.ToString());
            model.FilePath = fs.WriteTxt(arr, "TH" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".txt");

            if (string.IsNullOrWhiteSpace( model.FilePath)) return ApiFail("提交失败！");
            model.Type = 2;//退货
            model.EnterpriseId = userModel.EnterpriseId;
            model.CreateLoginID = userModel.UserID;
            model.CreateLoginName = userModel.LoginName;
            model.CreateDate = DateTime.Now;
            model.ViewDel = 0;
            int count = fs.SearchChildrenCount(model.Codes[0]);
            model.DragNum = count * model.Num;
            model.Num = arr.Length;
            model.DistributorId = userModel.Distributor;
            model.Status = 1;//待导入
            model.CheckStatus = 1;//待审核
            int m = _flee.ProReturnAdd(model);
            if (m <= 0)
            {
                return ApiFail("提交失败！");
            }

            //批量冻结
            fs.FrozenOrThaw(string.Join(",", arr), 1);
            //添加处理状态
            AntiFleeing_ProcessingType typeModel = new AntiFleeing_ProcessingType();

            typeModel.FormCode = model.FormCode;
            typeModel.Type = 2;//退货
            typeModel.ViewDel = 0;
            typeModel.CreateLoginID = userModel.UserID;
            typeModel.CreateLoginName = userModel.LoginName;
            typeModel.CreateDate = DateTime.Now;
            typeModel.Status = 0;//未审核
            typeModel.EnterpriseID = userModel.EnterpriseId;
            int n = _flee.ProcTypeAdd(typeModel);

            return ApiSuccess(true);

        }
    }
}
